package com.zpark.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zpark.utils.ResponseData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @PackageName: com.zpark.controller
 * @ClassName: SentinelController
 * @Description:
 * @author: RZS
 * @date: 2024/5/7  9:02
 */
@RestController
public class SentinelController {

    @GetMapping("/a")
    public ResponseData<String> testA(){

        return testASphU();
    }

    @GetMapping("/b")
    public ResponseData<String> testB(){

        return testBbySphO();
    }

    /**
     * 通过 SphO 手动定义资源
     *
     * @return
     */
    public ResponseData<String> testBbySphO() {
        if (SphO.entry("testBbySphO")) {
            // 务必保证finally会被执行
            try {
                System.out.println("服务访问成功------testB：");
            } finally {
                SphO.exit();
            }
        }else {
            // 资源访问阻止，被限流或被降级
            //流控逻辑处理 - 开始
            System.out.println("testB 服务被限流");
            return new ResponseData<>(2000, "SUCCESS", "请求服务B失败");
            //流控逻辑处理 - 结束
        }

        return new ResponseData<>(2000, "SUCCESS", "请求服务B成功");
    }

    /**
     * 通过 SphU 手动定义资源
     * @return
     */
    public ResponseData<String> testASphU(){

        Entry entry = null;
        try {
            // 设置资源的名字
            entry = SphU.entry("testAbySphU");
            //您的业务逻辑 - 开始
            System.out.println("服务访问成功------testA：");
            //您的业务逻辑 - 结束
        } catch (BlockException e1) {
            //流控逻辑处理 - 开始
            System.out.println("testA 服务被限流");
            return new ResponseData<>(2000, "SUCCESS", "请求服务A失败");
            //流控逻辑处理 - 结束
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }

        return new ResponseData<>(2000, "SUCCESS", "请求服务A成功");
    }
}
